package com.sogo;


import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.database.Cursor;

public class Registration extends Activity {
	private EditText etUsername;
	private EditText etPassword1;
	private EditText etPassword2;
	private EditText etFirstName;
	private EditText etLastName;
	private EditText etEmail1;
	private EditText etEmail2;
	private Button btnRegister;
	final DBAdapter db = new DBAdapter(this);
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registration);
		etUsername = (EditText)findViewById(R.id.userName);
		etPassword1=(EditText)findViewById(R.id.password1);
		etPassword2=(EditText)findViewById(R.id.password2);
		etEmail1=(EditText)findViewById(R.id.email1);
		etEmail2=(EditText)findViewById(R.id.email2);
		etFirstName=(EditText)findViewById(R.id.firstName);
		etLastName=(EditText)findViewById(R.id.lastName);
		btnRegister = (Button)findViewById(R.id.register_button);
		
        btnRegister.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String username = etUsername.getText().toString();
				String password1 = etPassword1.getText().toString();
				String password2 = etPassword2.getText().toString();
				String email1 = etEmail1.getText().toString();
				String email2 = etEmail2.getText().toString();
				String firstName=etFirstName.getText().toString();
				String lastName=etLastName.getText().toString();
				boolean validEmail1=validateEmail(email1);
				

				
				
				if (username.length()!=0&&password1.length()!=0&&password1.equals(password2)&&validEmail1==true
						&&email1.equals(email2)&&firstName.length()!=0&&lastName.length()!=0)
				{
						String userID = null;
					try {
						userID=new register(username,password1,email1,firstName,lastName).execute().get();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ExecutionException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					/*
					Toast toast;
					Context context=getApplicationContext();
					int duration=Toast.LENGTH_LONG;
					toast=Toast.makeText(context, "======="+userID+"======", duration);
					toast.show();*/

					Intent s = new Intent(getApplicationContext(), FriendsListMainScreen.class);
                    startActivity(s);
				}
				else
				{
					Toast toast;
					Context context=getApplicationContext();
					int duration=Toast.LENGTH_LONG;
					toast=Toast.makeText(context, "Please check your fields", duration);
					toast.show();
				}
			}	
		});
	}
	public static boolean validateEmail(String email) {
	    boolean isValid = false;

	    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
	    CharSequence inputStr = email;

	    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
	    Matcher matcher = pattern.matcher(inputStr);
	    if (matcher.matches()) {
	        isValid = true;
	    }
	    return isValid;
	}


	private class register extends AsyncTask<String,String,String>{
	    private ProgressDialog Dialog = new ProgressDialog(Registration.this);
	    private String username,password,email,firstName,lastName;
	    public register(String username1, String password1, String email1,
				String firstName1, String lastName1) {
			username=username1;
			password=password1;
			email=email1;
			firstName=firstName1;
			lastName=lastName1;
		}

		protected void onPreExecute() {
	        Dialog.setMessage("Please Wait Checking Credentials");
	        Dialog.show();
	    }
	
		protected String doInBackground(String... params) {
			JSONArray jsonArray;
			JSONObject json = new JSONObject();
			password=ServerConnection.encryptPassword(password);
			String userid = null;
			try{
				json.put("username", username);
				json.put("password", password);
				json.put("email", email);
				json.put("firstName", firstName);
				json.put("lastName", lastName);
				jsonArray=ServerConnection.CommunicateWithServer(json,1);
				json=jsonArray.getJSONObject(0);
				userid=json.getString("ID");
				//Log.i("registration words!",String.valueOf(userid));
				
                db.open();
                db.insertUser(Integer.parseInt(userid),username, firstName, lastName , email, password,"noimage"); //registration
                /*
                Cursor c = db.getUser();
                if (c.moveToFirst())
                {
                    do{
                        DisplayUser(c);
                   }while (c.moveToNext());
                }*/
                db.close();
			}catch (Throwable t) {
				
			}
			return userid;
		}
	    protected void onPostExecute(Void unused) {
	        Dialog.dismiss();
	
	    }
	}


    public void DisplayUser(Cursor c){
        Toast.makeText(this,
                "id: " + c.getString(0) + "\n" + "UserName: " + c.getString(1) + "\n" +
         "First Name: " + c.getString(2) + "\n" + "Last Name: " + c.getString(3)
         + "\n" + "Password: " + c.getString(4) + "\n" + "Email: " + c.getString(5), Toast.LENGTH_LONG).show();
    }
}
